package team.lhc.cms.config;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;


/*
上传图片到服务器
 */
public class QiniuUpload {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = "4HvvDA_oOvwKdGujQjA_5-_vfRHBex8AuC3c5KLi";
    private static String SECRET_KEY = "YH1aGzVHUHPNJ9hxn5OvFqXfxJ7TVgf4ahIXAd-Q";

    //要上传的空间
    private static String bucketname ="lengmao";
    //    七牛默认域名
    public static  String domain = "http://img.lengmaoking.com";

    //密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    private static Configuration cfg = new Configuration(Zone.huanan());

    //创建上传对象
    private static UploadManager uploadManager = new UploadManager(cfg);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken(){
        return auth.uploadToken(bucketname);
    }

    //上传
    public static String updateFile(MultipartFile file, String filename) throws Exception {
            try {
                Response response = uploadManager.put(file.getBytes(),filename,getUpToken());
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return domain+"/"+putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                }
            }
        return null;
    }
}
